package com.example.springboot.common.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.resp.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件接口
 */
@Tag(name = "文件操作")
@RestController
@RequestMapping("/files")
public class FileController {

    // 文件上传存储路径
    // private static final String filePath = System.getProperty("user.dir") + "/files/";
    private static final String filePath = "D:/websites/xhfh.book.plus" + "/files/";

    @Data
    private static class Res {
        private String url;
    }

    @Value("${server.port:9090}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    /**
     * 删除文件
     *
     * @param flag f
     */
    @Operation(summary = "删除文件")
    @DeleteMapping("/{flag}")
    public void delFile(@PathVariable String flag) {
        FileUtil.del(filePath + flag);
        System.out.println("删除文件" + flag + "成功");
    }

    /**
     * 文件上传
     */
    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) {
        String flag;
        synchronized (FileController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);  // ***/manager/files/1697438073596-avatar.png
            System.out.println(fileName + "--上传成功");
        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        String http = "http://" + "115.190.31.221" + ":" + port + "/files/";
        String address = http + flag + "-" + fileName;
        return Result.success(address);  //  http://localhost:9090/files/1697438073596-avatar.png
    }

    /**
     * 获取文件
     *
     * @param flag     f
     * @param response r
     */
    @Operation(summary = "获取文件")
    @GetMapping("/{flag}")   //  1697438073596-avatar.png
    public void filesPath(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        try {
            if (StrUtil.isNotEmpty(flag)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + flag);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * 图片上传
     * 地址为服务器任意地址
     * 需要使用nginx反向代理映射获取图片
     */
    @Operation(summary = "上传图片")
    @PostMapping("/uploadImage")
    public String uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            return "图片为空";
        }
        String originalFilename = file.getOriginalFilename();
        String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        assert originalFilename != null;
        String fileNameSuffix = "." + originalFilename.split("\\.")[1];
        String fileName = fileNamePrefix + fileNameSuffix;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        //String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";
        //String pre = applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() + "\\spring-ui\\src\\assets\\avatar\\";
        String pre = "D:\\";
        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
            //String replace = path.replace(applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() + "\\spring-ui\\src", "/src");
            String replace = path.replace("D:\\", "http://localhost/images/");
            return replace.replace("\\", "/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片上传失败";
    }


}
